/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package xmarti.vacaxm.client.connect;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import xmarti.vacaxm.action.ImplMaintenance;
import xmarti.vacaxm.beans.maintenance.Bull;
import xmarti.vacaxm.beans.maintenance.Calf;
import xmarti.vacaxm.beans.maintenance.Cow;
import xmarti.vacaxm.beans.maintenance.EnumGender;
import xmarti.vacaxm.client.maintenance.animal.JPAnimal;
import xmarti.vacaxm.client.sequence.JPSequencesType;
import xmarti.vacaxm.exception.ExceptionHibernateVacaxm;
import xmarti.vacaxm.utils.ButtonTabComponent;
import xmarti.vacaxm.utils.TDSLanguageUtils;
import xmarti.vacaxm.utils.UpdateAction;

/**
 *
 * @author xmarti
 */


public class FinestraPrincipal extends javax.swing.JFrame {

    /**
     * Creates new form FinestraPrincipal
     */
    //private JPanelMenu p2 = new JPanelMenu();
    private JTree jTreeMenu; 
    private ImplMaintenance implMaintenance;     
    private UpdateAction actions=null;
    private boolean isClosing;
    
    public FinestraPrincipal() {
        initComponents();    
        this.isClosing=false; 
        this.setTitle(TDSLanguageUtils.getMessage("jFrameMain.frame.caption"));
        this.implMaintenance= new ImplMaintenance(); 
        this.actions= new UpdateAction(); 
        DefaultMutableTreeNode top =
           new DefaultMutableTreeNode
            (TDSLanguageUtils.getMessage("jPanelMenu.jTreeVacaXM.Caption"));
        
        
        createNodes(top);        
        this.jTreeMenu= new JTree(top); 
        jTreeMenu.addTreeSelectionListener(new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent e) {
                try { 
                    treeValueChanged(e);
                } catch (ExceptionHibernateVacaxm ex) {
                    //todo cal implementar
                    Logger.getLogger(FinestraPrincipal.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        
        this.jTreeMenu.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);
       
        jScrollPane1.setViewportView(jTreeMenu);

        pack();
        setExtendedState(6);
    }

    public UpdateAction getActions() {
        return actions;
    }

    public void setActions(UpdateAction actions) {
        this.actions = actions;
    }
    
    public void treeValueChanged(TreeSelectionEvent e) throws ExceptionHibernateVacaxm {        
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                           this.jTreeMenu.getLastSelectedPathComponent();

        if (node == null) return;
        Object nodeInfo = node.getUserObject();
        if (node.isLeaf()) {
            NodeInfo leaf = (NodeInfo)nodeInfo;
            setAction(leaf.action);
        }
    }
    private int getTabIndex(String title){                
        for(int i =0; i<jTabbedPane.getTabCount();i++){
            if (jTabbedPane.getTitleAt(i).equals(title)) return i; 
        }        
        return -1; 
    }
    
    private void createNodes(DefaultMutableTreeNode top){
        DefaultMutableTreeNode category = null;
        DefaultMutableTreeNode category1 = null;
        DefaultMutableTreeNode leaf = null;
        category = new DefaultMutableTreeNode(TDSLanguageUtils.getMessage("jPanelMenu.jTreeVacaXM.maintenance.caption"));
        top.add(category);
        category1 = new DefaultMutableTreeNode(TDSLanguageUtils.getMessage("jPanelMenu.jTreeVacaXM.maintenance.animal.caption"));
        category.add(category1);
        leaf = new DefaultMutableTreeNode(new NodeInfo
            (TDSLanguageUtils.getMessage("jPanelMenu.jTreeVacaXM.maintenance.animal.cows.caption"),
            "selectCows"));
        
        category1.add(leaf);
        leaf = new DefaultMutableTreeNode(new NodeInfo
            (TDSLanguageUtils.getMessage("jPanelMenu.jTreeVacaXM.maintenance.animal.bulls.caption"),
            "selectBulls"));
        category1.add(leaf);
        leaf = new DefaultMutableTreeNode(new NodeInfo
            (TDSLanguageUtils.getMessage("jPanelMenu.jTreeVacaXM.maintenance.animal.calfs.male.caption"),
            "selectCalfsMale"));
        category1.add(leaf);
        leaf = new DefaultMutableTreeNode(new NodeInfo
            (TDSLanguageUtils.getMessage("jPanelMenu.jTreeVacaXM.maintenance.animal.calfs.female.caption"),
            "selectCalfsFemale"));
        category1.add(leaf);      
        
        category1 = new DefaultMutableTreeNode(TDSLanguageUtils.getMessage("jPanelMenu.jTreeVacaXM.maintenance.sequence.caption"));
        category.add(category1);
        leaf = new DefaultMutableTreeNode(new NodeInfo
            (TDSLanguageUtils.getMessage("jPanelMenu.jTreeVacaXM.maintenance.sequence.sequenceType.caption"),
            "selectSequencesType"));
        category1.add(leaf);        
        
        category=null;
        category1=null;
        leaf=null;         
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu3 = new javax.swing.JMenu();
        jMenu4 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jSplitPane1 = new javax.swing.JSplitPane();
        jTabbedPane = new javax.swing.JTabbedPane();
        jPanelMenu = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu5 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        jMenu3.setText("File");
        jMenuBar2.add(jMenu3);

        jMenu4.setText("Edit");
        jMenuBar2.add(jMenu4);

        jMenuItem1.setText("jMenuItem1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setExtendedState(6);
        setMaximumSize(new java.awt.Dimension(800, 600));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jSplitPane1.setDividerLocation(200);
        jSplitPane1.setOneTouchExpandable(true);

        jTabbedPane.setBackground(new java.awt.Color(237, 236, 233));
        jTabbedPane.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jTabbedPaneStateChanged(evt);
            }
        });
        jSplitPane1.setRightComponent(jTabbedPane);

        javax.swing.GroupLayout jPanelMenuLayout = new javax.swing.GroupLayout(jPanelMenu);
        jPanelMenu.setLayout(jPanelMenuLayout);
        jPanelMenuLayout.setHorizontalGroup(
            jPanelMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
        );
        jPanelMenuLayout.setVerticalGroup(
            jPanelMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelMenuLayout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 313, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(238, Short.MAX_VALUE))
        );

        jSplitPane1.setLeftComponent(jPanelMenu);

        jMenu5.setText("jMenu5");

        jMenuItem2.setText("jMenuItem2");
        jMenu5.add(jMenuItem2);

        jMenuBar1.add(jMenu5);

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
                .addGap(0, 0, 0))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jSplitPane1)
                .addGap(0, 0, 0))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTabbedPaneStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPaneStateChanged
        if (this.actions.isAction()){           
            for(int i=0; i<this.jTabbedPane.getTabCount();i++){
                    switch(this.jTabbedPane.getComponent(i).toString()){
                        case "JPANIMAL":
                                JPAnimal jp=  (JPAnimal) this.jTabbedPane.getComponent(i);
                                if (this.actions.isMothers())   jp.updateMother();
                                if (this.actions.isFathers())   jp.updateFather(); 
                                if (this.actions.isOrigins())   jp.updateOrigin(); 
                                if (this.actions.isDestinations())   jp.updateDestination(); 
                            break;                     
                    }                                     
            }
            this.actions.reset(); 
        }
    }//GEN-LAST:event_jTabbedPaneStateChanged

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
//         for(int i =0; i<jTabbedPane.getTabCount();i++){
//            jTabbedPane.getcom
//             
//        }      
    }//GEN-LAST:event_formWindowClosing
    
    private void setAction (String action){
        int i =-1;
        
        switch (action){
                case "selectCows":                                        
                    i = getTabIndex(TDSLanguageUtils.getMessage("jFrameMain.jTree.cow.caption"));
                    if (i>=0 ){
                        jTabbedPane.setSelectedIndex(i);
                    }else{                        
                        final JPAnimal p1= new JPAnimal(implMaintenance,this.actions,Cow.class.getName());
                        //JPCow p1= new JPCow(implMaintenance,this.actions);
                        jTabbedPane.add(p1,TDSLanguageUtils.getMessage("jFrameMain.jTree.cow.caption"));              
                        if(jTabbedPane.getTabCount()>0)
                        jTabbedPane.setTabComponentAt(jTabbedPane.getTabCount()-1,new ButtonTabComponent(jTabbedPane) {
                            @Override
                            public void setFormat() {
                                p1.setFormat();                                
                            }
                        });                        
                        jTabbedPane.setSelectedIndex(jTabbedPane.getTabCount()-1);                    
                    }                                       
                    break; 
                case "selectBulls":
                    i = getTabIndex(TDSLanguageUtils.getMessage("jFrameMain.jTree.bull.caption"));
                    if (i>=0 ){
                        jTabbedPane.setSelectedIndex(i);
                    }else{
                        final JPAnimal p1= new JPAnimal(implMaintenance,this.actions,Bull.class.getName());
                        jTabbedPane.add(p1,TDSLanguageUtils.getMessage("jFrameMain.jTree.bull.caption"));              
                        if(jTabbedPane.getTabCount()>0)
                        jTabbedPane.setTabComponentAt(jTabbedPane.getTabCount()-1,new ButtonTabComponent(jTabbedPane) {

                            @Override
                            public void setFormat() {
                                p1.setFormat();
                            }
                        });                        
                        jTabbedPane.setSelectedIndex(jTabbedPane.getTabCount()-1);                    
                    }
                    break;
                case "selectCalfsMale":
                    i = getTabIndex(TDSLanguageUtils.getMessage("jFrameMain.jTree.calf.male.caption"));
                    if (i>=0 ){
                        jTabbedPane.setSelectedIndex(i);
                    }else{                                                
                        final JPAnimal p1= new JPAnimal(implMaintenance,this.actions,Calf.class.getName(),EnumGender.MALE);
                        jTabbedPane.add(p1,TDSLanguageUtils.getMessage("jFrameMain.jTree.calf.male.caption"));              
                        if(jTabbedPane.getTabCount()>0)
                        jTabbedPane.setTabComponentAt(jTabbedPane.getTabCount()-1,new ButtonTabComponent(jTabbedPane) {

                            @Override
                            public void setFormat() {
                                p1.setFormat();
                            }
                        });                        
                        jTabbedPane.setSelectedIndex(jTabbedPane.getTabCount()-1);                                                                   
                    }
                    break;
                 case "selectCalfsFemale":
                    i = getTabIndex(TDSLanguageUtils.getMessage("jFrameMain.jTree.calf.female.caption"));
                    if (i>=0 ){
                        jTabbedPane.setSelectedIndex(i);
                    }else{                        
                        
                        final JPAnimal p1= new JPAnimal(implMaintenance,this.actions,Calf.class.getName(),EnumGender.FEMALE);
                        
                        jTabbedPane.add(p1,TDSLanguageUtils.getMessage("jFrameMain.jTree.calf.female.caption"));              
                        if(jTabbedPane.getTabCount()>0)
                        jTabbedPane.setTabComponentAt(jTabbedPane.getTabCount()-1,new ButtonTabComponent(jTabbedPane) {

                            @Override
                            public void setFormat() {
                                p1.setFormat();
                            }
                        });                        
                        jTabbedPane.setSelectedIndex(jTabbedPane.getTabCount()-1);                                                                
                    }
                    break;
                 case "selectSequencesType":
                     i = getTabIndex(TDSLanguageUtils.getMessage("jFrameMain.jTree.sequence.sequenceType.caption"));
                    if (i>=0 ){
                        jTabbedPane.setSelectedIndex(i);
                    }else{                        
                        
                        final JPSequencesType p1= new JPSequencesType();
                        
                        jTabbedPane.add(p1,TDSLanguageUtils.getMessage("jFrameMain.jTree.sequence.sequenceType.caption"));              
                        if(jTabbedPane.getTabCount()>0)
                        jTabbedPane.setTabComponentAt(jTabbedPane.getTabCount()-1,new ButtonTabComponent(jTabbedPane) {

                            @Override
                            public void setFormat() {
                                p1.setFormat();
                            }
                        });                        
                        jTabbedPane.setSelectedIndex(jTabbedPane.getTabCount()-1);                                                                
                    }
                     break;
                    
            };
    }
        
    
         
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */

        /*javax.swing.UIManager$LookAndFeelInfo[Metal javax.swing.plaf.metal.MetalLookAndFeel]
         javax.swing.UIManager$LookAndFeelInfo[Nimbus javax.swing.plaf.nimbus.NimbusLookAndFeel]
         javax.swing.UIManager$LookAndFeelInfo[CDE/Motif com.sun.java.swing.plaf.motif.MotifLookAndFeel]
         javax.swing.UIManager$LookAndFeelInfo[Windows com.sun.java.swing.plaf.windows.WindowsLookAndFeel]
         javax.swing.UIManager$LookAndFeelInfo[Windows Classic com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel]
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {

                //System.out.println(info.toString());
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FinestraPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FinestraPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FinestraPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FinestraPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                TDSLanguageUtils.setDefaultLanguage("xmarti/vacaxm/i18n/messages");

                new FinestraPrincipal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenu jMenu5;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanelMenu;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTabbedPane jTabbedPane;
    // End of variables declaration//GEN-END:variables

    
    
    private class NodeInfo {
        public String name;
        public String action;

        public NodeInfo(String name, String action) {
            this.name = name;
            this.action=action;
        }

        @Override
        public String toString() {
            return this.name;
        }
    }
}
